import { defineStore } from 'pinia'

import { getUserMenu } from 'jax-node/api/admin'
import { eachTree } from 'jax-admin/utils/utils'

import config from '@/config'

export const useMenuStore = defineStore('menuStore', () => {
  const homeUrl = ref('')
  const menuList = ref([])

  const route = useRoute()
  const router = useRouter()

  const basePath = config?.base + '/'

  const activePath = computed(() => {
    if (route.query.rootPath) {
      return route.query.rootPath
    } else if (route.meta.rootPath) {
      return route.meta.rootPath[0] != '' ? basePath + route.meta.rootPath : route.meta.rootPath
    } else {
      return route.path
    }
  })

  const getMenu = () => {
    homeUrl.value = null

    return getUserMenu().then(res => {
      eachTree(res, item => {
        if (item.path) {
          item.path = item.path[0] != '/' ? basePath + item.path : item.path
          if (!homeUrl.value) homeUrl.value = item.path
        }
      })
      menuList.value = res
    })
  }

  const onSelect = path => router.push(path)

  return {
    homeUrl,
    menuList,
    activePath,

    getMenu,
    onSelect,
  }
})

export default useMenuStore
